/**
 * @author zhangqiang
 * @date   17/7/20
 */
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Toast,Popup} from 'antd-mobile'
import {Title} from '../../components/common'
//通用组件
import BottomMenu from '../../../../../../../src/js/components/bottomMenu';
import '../../../styles/checkExpress.scss'
import {InputItem,FooterAlertMask} from '../../components/home'
import {checkExpress} from '../../actions/checkExpress'
import common from '../../utils/common'
import style from './index.scss'

class CheckExpress extends Component {
	constructor(props) {
	super(props);
		this.state={
			express: {
				com: 'EMS',
				no: 'ems'
			},
			courierCodeIconType: '', //邮件号状态
			expressHistoryList: [],//历史数据
			courierCodeValue: '',//邮政号
			expressCompany: [   //取证方式
				{times: 'ems', timesName: 'EMS',},
				{times: 'emsg', timesName: 'EMS国际',}
			],
		}
	}

	componentWillMount() {
		common.setViewTitle('查快递');
	}

	componentDidMount() {
		let that = this;
		let expressHistory = JSON.parse(sessionStorage.getItem('expressHistory'))||[],
			expressService = sessionStorage.getItem('expressService')?
								sessionStorage.getItem('expressService'):
								{"com":"EMS","no":"ems"},
			statePage = sessionStorage.getItem('cacheCheckExpress');  //状态
			
		this.setState({
			expressHistoryList: expressHistory,
			express: expressService
		})

		this.setState(
			Object.assign({}, JSON.parse(statePage))
		)

		document.getElementById('inputItemBox').style = 'height: 0.88rem'
	}

	componentWillUnmount() {
		sessionStorage.setItem('cacheCheckExpress',JSON.stringify(this.state))
	}

	componentDidUpdate() {
		/*
		* 兼容ios点击输入框遮挡tag
		* */
		// let inputAll = document.getElementsByTagName('input');
		// for(let i=0;i<inputAll.length;i++){
		// 	if(inputAll[i].type != 'checkbox'){ //复选框不用设置样式
		// 		inputAll[i].onfocus = () => {
		// 			document.querySelector('.footNavPoise').style.position='static'
		// 		}
		// 		inputAll[i].onblur = () => {
		// 			document.querySelector('.footNavPoise').style.position='fixed'
		// 		}
		// 	}
		// }
	}

	getExpressCompany(comNo,emsNo,comName) {
		console.log(comNo,emsNo,comName)
		let express = {
			com: comNo,
			comname: comName,
			no: emsNo
		}
		this.setState({
			express: express,
			courierCodeValue: comName
		})
	}

	//清除输入框内容
	closeInputText() {
		this.setState({
			courierCodeValue: '',
			courierCodeIconType: ''
		});
	}

	setHistory(value){
		var queryHistory = sessionStorage.getItem('expressHistory') == null||!sessionStorage.getItem('expressHistory')?new Array():
						JSON.parse(sessionStorage.getItem('expressHistory'));
			
		if(!this.isExistsInArray(queryHistory, value)){//先判断是否已存在缓存中，存在就删除，重新入队
			console.log(queryHistory.length == 10)
            if(queryHistory.length == 10){
                queryHistory.pop();//出队
			}
        }else{
			queryHistory = this.removeByValue(queryHistory,value);
		}
        queryHistory.unshift(value);//入队
		sessionStorage.setItem('expressHistory',JSON.stringify(queryHistory))

		this.setState({
			expressHistoryList: queryHistory
		})
	}

	//删除数组中某个值
    removeByValue(arr, val) {
		for(var i=0; i<arr.length; i++) {
			if(arr[i].comName == val.comName&&arr[i].comNo == val.comNo){
				arr.splice(i, 1);
				return arr;
			}
		}
		return arr;
        
	}
	
	 //判断是否存在数组中
	isExistsInArray(array,value) {
		for(var i=0; i<array.length; i++) {
			if(array[i].comName == value.comName&&array[i].emsNo == value.emsNo) {
				return true;
			}
		}
		return false;
	}

	//清除邮政号历史记录
	cleanCache(){
		sessionStorage.removeItem('expressHistory')
		this.setState({
			expressHistoryList: []
		})
	}

	//底部跳转
	bottomHandle(index) {
		console.log('checkExpress',index)
		if (index == 0) {
			this.props.router.push('/');
		} else if (index == 1) {
			this.props.router.push('checkExpress');
		} else {
			this.props.router.push('orderList');
		}
	}

	/**
	 *  选择快递公司
	 */
	selectExpressCompany() {
		let props = {
			data: this.state.expressCompany,
			timesIndex: this.state.express.no,   //默认选项
			onChoose: (times,timesName) => {
				console.log(times)
				console.log(timesName)
			
				this.setState({
					express: {
						com: timesName,
						no: times
					},
				})
				Popup.hide(); //隐藏
			}
		};
		const y = scrollY
		Popup.show(<FooterAlertMask {...props}/>, {animationType: 'slide-up'});
		scrollTo(undefined, y)
	}

	handle(){
		let { courierCodeValue, express } = this.state;
		let history = {
			comNo: express.com,
			comName: courierCodeValue,
			emsNo: express.no
		}
		
		if (courierCodeValue == '') {
			Toast.info('请输入邮件号',1)
			return;
		}
		this.setHistory(history);
		let postData = {
			comName: express.com,
			comNo: express.no,
			inputValue: courierCodeValue  
		}
		this.props.dispatch(checkExpress(postData,(resultData)=>{
			let infoList = resultData.infoList;
			if(infoList){					
				postData['infoList'] = infoList
				sessionStorage.setItem('checkProgress', JSON.stringify(postData));
				this.props.router.push('checkProgress');
			}else{
				Toast.info('未查到该邮件的进度，请确认邮件号是否填写正确！',2);					
			}
		}))
	}

	render() {
		let { expressHistoryList, express } = this.state;
		return (
			<div className={style.checkExpress}>
				<div className={style.inputContainer}>
					<div className={style.expressServices} onClick={e => this.selectExpressCompany()}>
						{express.com}
						<img src="./images/icon_to_r.png" alt=""/>
					</div>
					<div style={{height: '.32rem'}}></div>
					<div className={style.courierNum}>
						<InputItem type="text" index='2' itemText="" maxLength="20" placeHolder="请输入邮件号" id="creditCode"
							value={this.state.courierCodeValue} showUnderLine={false} showTagText={false} creditCodeImg={this.state.nameImg} creditWidth = {this.state.nameWidth}
							onClick={()=>{
								this.setState({
									courierCodeValue: '',
									nameImg: 'hideDelete',
									nameNoBlur: false
								})
								document.querySelector('#creditCode').focus();
							}}
							onBlur={(event)=>{
								let res = event.target.value;
								this.setState({nameNoBlur: true});
								setTimeout(()=>{
									if(!this.state.nameNoBlur) return;  //点击删除按钮不执行验证
									let value = res,
										nameRule1= /^[\u4e00-\u9fa5]{2,12}$/;

									if(value == ''){
										this.setState({
											nameImg: '',
										});
									}else if(value != ''){
										this.setState({
											nameImg: 'correct',
											nameWidth: '.4rem'
										});
									}else {
										this.setState({
											nameWidth: '.4rem',
											nameImg: 'error'
										})
									}
								},0)
							}}

						onFocus={(e)=>{
							let value = e.target.value;
							if(value.length!=0&&this.state.courierCodeValue==value){
								this.setState({
									nameImg: 'showDelete',
								});
							}
						}}
						onChange={(e) => {
							let value = e.target.value.replace(/(^\s*)|(\s*$)/g, "").replace(/[^\w\.\/]/ig,'').toUpperCase();
							if(value.length>0&&value!=' '){
								this.setState({
									nameImg: 'showDelete',
									courierCodeValue: value
								});
							}else {
								this.setState({
									nameImg: 'hideDelete',
									courierCodeValue: value
								});
							}
						}}/>
					</div>
					<div style={{height: '.4rem'}}></div>
					<div className={style.btnBox}>
            			<button type="button" className={style.handle} onClick={e => this.handle()}>查询</button>
        			</div>
				</div>

				{/* 历史记录 start */}
				<div style={!expressHistoryList.length?{display: 'none'}:{}}>
					<Title text='查询历史' isLine={true}/>
					<div className={style.historicalRecords}> 
						{
							expressHistoryList.map((item,index)=>{
								return <div key={index}>
									<div className={style.courierItem} onClick={e => this.getExpressCompany(item.comNo,item.emsNo,item.comName)}>
										<img className={style.query} src="./images/checkEms.png"></img>
										{item.comNo} {item.comName}
									</div>
								</div>
							})
						}				
						<div className={style.reset} onClick={e => this.cleanCache()}>清空历史</div>
					</div>
				</div>
				{/* 历史记录 end*/}
				<div style={{height: '1.2rem'}}></div>

				{/*底部导航菜单 start checkEms_checked*/}
				<BottomMenu active={1} onChange={(index) => {
					this.bottomHandle(index);
				}} data={[{
					text: '寄快递',
					img: './images/sendEms.png',
					checkedImg: './images/sendEms_checked.png'
				},{
					text: '查快递',
					img: './images/checkEms.png',
					checkedImg: './images/checkEms_checked.png'
				},{text: '我的订单', img: './images/my.png', checkedImg: './images/my_checked.png'}]}/>
				{/*底部导航菜单end*/}
			</div>
		)
    }
}

//使用context
CheckExpress.contextTypes = {
    router: React.PropTypes.object.isRequired
};

export default connect()(CheckExpress);
